package com.vipyinzhiwei.android.sample;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vipyinzhiwei.android.GlobalApplication;
import com.vipyinzhiwei.android.R;
import com.vipyinzhiwei.android.library.Alert;
import com.vipyinzhiwei.android.library.AppEnvironment;
import com.vipyinzhiwei.android.library.Logger;
import com.vipyinzhiwei.android.library.base.adapter.BaseMAdapter;
import com.vipyinzhiwei.android.library.base.bean.AdapterModelBean;
import com.vipyinzhiwei.android.library.base.ui.CommonActivity;
import com.vipyinzhiwei.android.library.sharesdk.UmengShareHelper;
import com.vipyinzhiwei.android.library.tools.ToolPhone;
import com.vipyinzhiwei.android.library.tools.ToolToast;
import com.vipyinzhiwei.android.library.tools.permission.PermissionConstants;
import com.vipyinzhiwei.android.library.tools.permission.ToolPermission;
import com.vipyinzhiwei.android.library.umeng.statistics.UmengMobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * Sample列表集合界面--自动收集AndroidManifest.xml配置
 * <per>
 * <intent-filter>
 * <action android:name="android.intent.action.MAIN" />
 * <category android:name="com.vipyinzhiwei.android.SAMPLE_CODE" />
 * </intent-filter>
 * </per>
 * 的Activity
 *
 * @author 曾繁添
 * @version 1.0
 */
public class MainActivity extends CommonActivity implements View.OnClickListener {
    /**
     * 左侧布局
     */
    private DrawerLayout mDrawerLayout;

    private ListView mListView;
    public final static String SAMPLE_CODE = "com.vipyinzhiwei.android.SAMPLE_CODE";

    @Override
    public void config(Bundle savedInstanceState) {
        super.config(savedInstanceState);
        //ToolPhone.setTransulcentStatusBar(this,mWindowTitle);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initParams(Bundle params) {
        super.initParams(params);
        //设置tag
//		BuglyReport.setUserSceneTag(getContext(), 17459);
    }

    @Override
    public void initView(View view) {
        String strCenterTitle = getResources().getString(R.string.MainActivity);
        mWindowTitle.initBackTitleBar("vipyinzhiwei-" + strCenterTitle, Gravity.CENTER);
        mWindowTitle.getDoneImageButton().setVisibility(View.INVISIBLE);
        mWindowTitle.getBackImageButton().setImageResource(R.drawable.anl_common_nav_menu_white_n);

        mWindowTitle.getBackImageButton().setOnClickListener(this);

        mDrawerLayout = findViewById(R.id.id_drawer_layout);

        mListView = (ListView) findViewById(R.id.lv_demos);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ActivityItem data = (ActivityItem) parent.getItemAtPosition(position);
                Intent intent = data.intent;
                getOperation().forward(intent.getComponent().getClassName(), LEFT_RIGHT);

                UmengMobclickAgent.onEvent(MainActivity.this, "vipyin");
                UmengMobclickAgent.onEvent(MainActivity.this, "hello_world");
            }
        });

        //构造适配器
        DemoActivityAdapter mAdapter = new DemoActivityAdapter(this);
        mAdapter.addItem(getListData());
        mListView.setAdapter(mAdapter);

        //是否Root
        Toast.makeText(mActivity, "当前手机root状态：" + ToolPhone.isRootSystem(), Toast.LENGTH_SHORT)
                .show();
    }

    @Override
    public void doBusiness(Context mContext) {
        ToolPhone.setStatusBarBackgroundColor(this, getResources().getColor(R.color
                .common_module_actionbar_bg));

        try {
            //获取运行环境
            boolean isEmulator = AppEnvironment.isEmulator(getContext());
            Alert.toastLong("当前运行环境：" + (isEmulator ? "模拟器" + "(" + AppEnvironment.OS_VERSION +
                    ")" : (AppEnvironment.MODEL_NUMBER + "(" + AppEnvironment.OS_VERSION + ")")));

            //获取渠道号
            Alert.toastShort("应用渠道号：" + GlobalApplication.channelId);
        } catch (Exception e) {

        }

//        requestPermissions();
    }

    /**
     * 申请应用所需权限
     */
    public void requestPermissions() {
        List<String> permissions = ToolPermission.getPermissions(this);
        Logger.d(TAG,permissions.toString());

        ToolPermission.permission(this, permissions.toArray(new String[]{})).callback(new ToolPermission.FullCallback() {

            @Override
            public void onGranted(List<String> permissionsGranted) {
                Logger.d(TAG,"获取权限成功");
            }

            @Override
            public void onDenied(List<String> permissionsDeniedForever, List<String>
                    permissionsDenied) {
                Logger.e(TAG,"获取权限失败");
            }
        }).request(this);
    }

    /**
     * 初始化列表数据
     *
     * @return
     */
    protected List<ActivityItem> getListData() {
        List<ActivityItem> mListViewData = new ArrayList<>();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(SAMPLE_CODE);
        List<ResolveInfo> mActivityList = getPackageManager().queryIntentActivities(mainIntent, 0);
        for (int i = 0; i < mActivityList.size(); i++) {
            ResolveInfo info = mActivityList.get(i);
            String label = info.loadLabel(getPackageManager()) != null ? info.loadLabel
                    (getPackageManager()).toString() : info.activityInfo.name;
            ActivityItem temp = new ActivityItem();
            temp.title = label;
            temp.intent = buildIntent(info.activityInfo.applicationInfo.packageName, info
                    .activityInfo.name);
            mListViewData.add(temp);
        }

        return mListViewData;
    }

    /**
     * 构建每一个Item点击Intent
     *
     * @param packageName
     * @param componentName
     * @return
     */
    protected Intent buildIntent(String packageName, String componentName) {
        Intent result = new Intent();
        result.setClassName(packageName, componentName);
        return result;
    }

    /**
     * 列表适配器
     */
    protected class DemoActivityAdapter extends BaseMAdapter {

        public DemoActivityAdapter(Activity mContext) {
            super(mContext);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Holder mHolder = null;
            if (null == convertView) {
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout
                        .activity_main_list_item, null);
                mHolder = new Holder();
                mHolder.label = (TextView) convertView.findViewById(R.id.tv_label);
                convertView.setTag(mHolder);
            } else {
                mHolder = (Holder) convertView.getTag();
            }

            //设置隔行变色背景
//			if(position%2==0){
//				convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
//			}else{
//				convertView.setBackgroundColor(Color.parseColor("#CCCCCC"));
//			}

            //设置数据
            ActivityItem data = (ActivityItem) getItem(position);
            mHolder.label.setText(data.title);

            return convertView;
        }

        class Holder {
            TextView label;
        }
    }

    class ActivityItem extends AdapterModelBean {
        String title;
        Intent intent;

        public ActivityItem() {
        }

        public ActivityItem(String title, Intent intent) {
            this.title = title;
            this.intent = intent;
        }
    }

    /**
     * Actionbar点击[左侧图标]关闭事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//				finish();
                break;
        }
        return true;
    }

    private boolean isQuit;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (isQuit == false) {
                isQuit = true;
                Toast.makeText(getBaseContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isQuit = false;
                    }
                }, 2000);
            } else {
                ((GlobalApplication) getApplication()).exit();
            }
        }
        return true;
    }


    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == com.vipyinzhiwei.android.library.R.id.ib_back) {
            if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
                mDrawerLayout.closeDrawer(Gravity.START);
            } else {
                mDrawerLayout.openDrawer(Gravity.START);
            }
        }
    }
}
